﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web;
using System.Web.Mvc;
using Newtonsoft.Json;

namespace MyMainSite2.Library.MVC
{
	public class JSONResult : ActionResult
	{
		#region Structs

		public struct OuterDataStruct
		{
			// camel case because these values will be used in JSON
			public bool hasError;
			public object data;
			public string errorMessage;
		}

		#endregion

		#region Properties

		public object Data
		{
			get { return _data; }
			private set { _data = value; }
		}
		private object _data = null;

		public OuterDataStruct OuterData
		{
			get { return _outerData; }
			private set { _outerData = value; }
		}
		private OuterDataStruct _outerData = new OuterDataStruct();

		#endregion

		#region Public Methods

		public JSONResult(object data)
		{
			this.Data = data;

			var hasError = this.Data is Exception;

			string errorMessage = String.Empty;
			if (hasError)
			{
				Exception ex = this.Data as Exception;
				errorMessage = ex.Message;
			}

			this.OuterData = new OuterDataStruct()
			{
				hasError = hasError,
				data = hasError ? null : this.Data, // there is no need to write the inners of the exception
				errorMessage = errorMessage,
			};
		}

		public override void ExecuteResult(ControllerContext context)
		{
			if (context == null)
				throw new ArgumentNullException("context");

			var json = JsonConvert.SerializeObject(this.OuterData, Formatting.Indented);

			var response = context.HttpContext.Response;

			response.Clear();
			response.Write(json);
		}

		#endregion
	}
}
